﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.Schedule;

namespace TimeJob.Application
{
    public class JobService : IDynamicApiController
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly string jobId = "j1";
        private readonly string triggerId = "t1";

        public JobService(ISchedulerFactory schedulerFactory)
        {
            _schedulerFactory = schedulerFactory;

            // 也可以通过 App.GetService<ISchedulerFactory>() 获取
        }


        public object Get()
        {
            _schedulerFactory.GetJobs();
           return _schedulerFactory.GetJob(jobId);


        }

        /// <summary>
        /// 动态创建job执行计划
        /// </summary>
        /// <returns></returns>
        public ScheduleResult Add()
        {
            DateTime time = DateTime.Now.AddSeconds(10);
            TriggerBuilder tb = TriggerBuilder.Create(triggerId)
                .SetStartTime(time)
                .SetNextRunTime(time)
                .SetNumberOfRuns(1)
                .SetResetOnlyOnce(true)
                .SetRunOnStart(true);
            var jobBuilder = JobBuilder.Create(jobId);
            jobBuilder.SetDescription(123.ToString());
            jobBuilder.SetJobType<MyJob>();
            ScheduleResult r =  _schedulerFactory.TryAddJob(jobBuilder, [tb], out IScheduler scheduler);
            
            return r;
           
        }

        /// <summary>
        /// 动态创建job执行计划
        /// </summary>
        /// <returns></returns>
        public object Delete()
        {
            TriggerBuilder[] triggerBuilder = { Triggers.PeriodSeconds(5) };

            var r = _schedulerFactory.TryRemoveJob(jobId, out IScheduler scheduler);

            return r.ToString();

        }
    }
}